import { subOrder, notifyOrderCmb ,checkIspay} from '@/common/userApi'
import { postOrderType, userorder } from '@/common/utils/userType'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const userorderStore = defineStore('order', {
  state: (): userorder => {
    return {
      orderData: localStorage.getItem('orderData') as any,
      qrCode: '',
      paymentcode: '',
      orderId:''
    }
  },
  actions: {
    // 改变orderData
    async updataPostOrderData(obj: postOrderType) {
      this.orderData = JSON.stringify(obj)
    },
    async postOrderFunction(obj: postOrderType) {
      subOrder(obj).then((res: any) => {
        console.log(res.data);
        if (res.code == 200) {
          this.orderId = res.data.id
          this.notifyOrderCmbcode(res.data.id)
        }
      });
    },
    async notifyOrderCmbcode(id: number) {
      this.orderId = id+''
      notifyOrderCmb(id).then((res: any) => {
        if (res.code == 200) {
          console.log(res.data)
          this.qrCode = res.data.qrCode 
          this.startLoop()         
        }
      });
    },
    // 定时器
    startLoop() {
     const intervalId = window.setInterval(() => {
        // 执行的动作
        console.log("循环执行中...");
        checkIspay(this.orderId).then((result) => {
                  type Easing = 'W' | 'P';
          this.paymentcode = result.data.code as Easing;      
                  console.log(result.data.code != 'W')
                  if (this.paymentcode != 'W') {
                    if (this.paymentcode != 'P') {
                        
                        clearInterval(intervalId); 
                      }              
                    }else {
                      console.log("继续执行")
                  }
                  localStorage.setItem('paymentcode', result.data.code);
        })
    }, 2000);
}
 
  }
})
